	var rootPath = getRootPath();
/**
 * 养修预约画面JS
 */
$(document).ready(function(){
	
	//养修预约的主DIV展现
	$("#maintainMainDiv").addClass("active in");
	
	
	// 经销商代码
	var dealerCode = getQueryParamValue("dealerCode");
	// 品牌代码
	var brandCode = getQueryParamValue("brandCode");
	// 服务顾问
	var serviceAdvisorCode = getQueryParamValue("serviceAdvisorCode");
	var openId = getQueryParamValue("openId");
	
	// 给hidden变量赋值
	if (openId!=null && openId != ''){
		$("#openId").val = openId;
	}
	if (dealerCode!=null && dealerCode != ''){
		$("#dealerCode").val = dealerCode;
	}
	if (brandCode!=null && brandCode != ''){
		$("#brandCode").val = brandCode;
	}
	if (serviceAdvisorCode!=null && serviceAdvisorCode != ''){
		$("#serviceAdvisorCode").val = serviceAdvisorCode;
	}
	


	
	$.ajax({
        type:"GET", 
        url:rootPath+"/wechat/api/maintain/getBindCarInfos", 
        dataType:"json",      
        async: false,
        contentType:"application/json",               
        data:null, 
        success:function(data){ 
        	if (data.length==0){
        		alert("您还没有绑定车辆，请先绑定车辆。");
        		to_bingCar();
        	}
            // 编辑轮播信息数据
			var wholeHtml = '';
			// 轮播（Carousel）指标
			var carousel_indicatorsHtml = '<ol class="carousel-indicators">';
			
			// 轮播（Carousel）项目
			var carousel_innerHtml = '<div class="carousel-inner">';
			
			var indexTemp= 0;
			$.each(data,function(carModelIndex,carModelObj){
				indexTemp = carModelIndex;
				if (0 == carModelIndex){
					
//				    carousel_indicatorsHtml+= '<li data-target="#myCarInfos" data-slide-to='+carModelIndex+' class="active"></li>';
					carousel_indicatorsHtml += '<li class="active"><a href="#" class="active" onclick=setVin('+carModelIndex+')><img alt="" src="'+rootPath+'/images/'+carModelObj.brandName+'/外观/'+carModelObj.seriesName+'/'+carModelObj.seriesName+'.jpg'+'"  data-target="#myCarInfos" data-slide-to="'+ carModelIndex +'" class="img-responsive"/ ></a></li>';
				    carousel_innerHtml += "<div class='item active'>";
				    //品牌CODE赋值
				    $("#vin").val(carModelObj.vin);
				    $("#modelName").val(carModelObj.modelName);
				} else {
//					carousel_indicatorsHtml+= '<li data-target="#myCarInfos" data-slide-to='+carModelIndex+' ></li>';
					carousel_indicatorsHtml += '<li><a href="#" onclick=setVin('+carModelIndex+')><img alt="" src="'+rootPath+'/images/'+carModelObj.brandName+'/外观/'+carModelObj.seriesName+'/'+carModelObj.seriesName+'.jpg'+'"  data-target="#myCarInfos" data-slide-to="'+carModelIndex+'" class="img-responsive"/ ></a></li>';
					carousel_innerHtml += "<div class='item'>";
				}
				
				carousel_innerHtml += '<table><tr>';
				carousel_innerHtml +="</td><td nowrap='nowrap' align='center' valign='middle'><div class=''>";
				carousel_innerHtml += "<p>";
				carousel_innerHtml +="<h4  style='font: bolder;color: #000'>"+carModelObj.registNo+"</h4>";
				carousel_innerHtml +="<span class='text-muted'>"+carModelObj.seriesName+"</span>";
				carousel_innerHtml +='<td width="70%"><img src="'+rootPath+'/images/'+carModelObj.brandName+'/外观/'+carModelObj.seriesName+'/'+carModelObj.seriesName+'.jpg'+'" width="150" height="70">';
				carousel_innerHtml +="</div></td></tr></table>";
				carousel_innerHtml +="<input type='hidden' id = 'vin_"+carModelIndex+"' value='"+carModelObj.vin+"' />";
				carousel_innerHtml +="<input type='hidden' id = 'modelName_"+carModelIndex+"' value='"+carModelObj.modelName+"' /></div>";
			});
			
			carousel_innerHtml += "<div class='item'>";
			carousel_innerHtml += "<table><tr><td width='70%'><a href='#' onclick='to_bingCar()' >";
			carousel_innerHtml += '<img src="'+rootPath+'/images/allCar.png'+'" width="150" height="70">';
			carousel_innerHtml +="</a></td><td nowrap='nowrap' align='center' valign='middle'><div class=''>";
			carousel_innerHtml += "<p>";
			carousel_innerHtml +="<h5  style='font: bolder;color: #000'><a href='#' onclick='to_bingCar()' >　绑定车辆？</a></h5>";
			carousel_innerHtml +="</div></td></tr></table>";
			carousel_innerHtml +="<input type='hidden' id = 'vin_"+indexTemp+1+"' value='' />";
			carousel_innerHtml +="<input type='hidden' id = 'modelName_"+indexTemp+1+"' value='' /></div>";
			
			
			carousel_indicatorsHtml += "</ol> ";
			carousel_innerHtml += "</div>";
			
			// 轮播（Carousel）导航
//			var carousel_controlHtml = '<a class="carousel-control left"  href="#myCarInfos"  data-slide="prev" type = "button">&lsaquo;</a>';
//			    carousel_controlHtml += '<a class="carousel-control right" href="#myCarInfos"  data-slide="next" type = "button">&rsaquo;</a>';
//			
			$("#myCarInfos").append(carousel_indicatorsHtml);
			$("#myCarInfos").append(carousel_innerHtml);
			
			// 停止自动轮播
			$('#myCarInfos').carousel({
				interval: false
			})
			// 停止自动轮播
			$("#myCarInfos").carousel('pause');
			
/////////////////////////////////////
			
			$('#myCarInfos').hammer().on('swipeleft', function(){
				$(this).carousel('next');
			});
			
			$('#myCarInfos').hammer().on('swiperight', function(){
				$(this).carousel('prev');
			});

////////////////////////////////////
        	
        },
        error:function(data){
        	alert("数据刷新失败，请联系管理员！");
        }
     });
	
	
	
	
	// 服务顾问信息取得。
	
	$.ajax({
        type:"GET", 
        url:rootPath+"/wechat/api/potentialUsers/counselor/selectCounselor?positionId=602", 
        dataType:"json",      
        async: false,
        contentType:"application/json",               
        data:null, 
        success:function(data){ 
			var options = [];
			options.push('<option userName="" phone="" value="0">请选择您的服务顾问</option>');
			$.each(data,function(carModelIndex,advisersObj){
				options.push("<option userName='"+advisersObj.userName+"' phone='"+advisersObj.phone+"' value='" + advisersObj.userId  +"'>"+advisersObj.userName+"</option>");
			});
			$("#seviceUser").append(options.join(""));
        },
        error:function(data){
        	alert("数据刷新失败，请联系管理员！");
        }
     });
	

	// 预约确定按钮
	$("#immediatelyAppoint").click(function(){
		if(!validat()){
			return;
		}
		if (null == $("#vin").val() || ''==$("#vin").val()){
			alert("请先选择需要养修的的车辆！");
			return;
		}
		
		var counselorPhone = $("#seviceUser").find("option:selected").attr("phone");
		var counselorName = $("#seviceUser").find("option:selected").attr("userName");
		 
		if(counselorPhone!=undefined && counselorPhone!=''){
			var salesConsultantPhone = counselorPhone;
		}
		if(counselorName!=undefined && counselorName!=''){
			var salesConsultantName = counselorName;
		}

		var maintainDto ={"vin":$("#vin").val(),"appointType":$("#appointType").val(),"reseApplStartTime":$("#maintainDate").val()+" "+$("#maintainTime").val(),
				"mileage":$("#mileage").val(),"maintainName":$("#maintainName").val(),"phone":$("#phone").val(),"salesConsultantId":$("#seviceUser").val(),
				"sourceType":$("#sourceType").val(),"remarks":$("#remarks").val(),"modelName":$("#modelName").val(),"salesConsultantPhone":salesConsultantPhone,
				"salesConsultantName":salesConsultantName,"appointTypeName":$("#appointType").find("option:selected").text()
		};
	$.ajax({ 
        type:"POST", 
        url:rootPath+"/wechat/api/maintain/saveMaintain", 
        dataType:"json",      
        contentType:"application/json",               
        data:JSON.stringify(maintainDto), 
        success:function(data){ 
        	if (0 != data.errorCode){
        		alert("预约失败！"+ data.errorMsg);
        	} else {
    			$('#sureModal').modal({
    				keyboard: false,
    				backdrop:false
    			});
        	}
        },
        error:function(data){
        	alert("预约失败！");
        }
     });
	
	});
	

	//选择日期时间
    var now = new Date();
    var currYear = now.getFullYear();	
    //选择日期
    $('#maintainDateSelectText').mobiscroll().date({
        theme: 'ios',
        lang: 'zh',
        display: 'bottom',
        mode: 'datetimeDate',
        min: new Date(now.getFullYear(), now.getMonth(), now.getDate()),
        startYear: currYear,
        dateFormat:'yyyy-mm-dd'
    
    });
    
});

//选择养修预约时间，点击
function selectMaintainTime(obj){
	 $("#maintainMainDiv").removeClass("active in");
	 $("#maintainDateSelDiv").show();
	 //初始化界面
	 $("#maintainDateSelectText").val("");
	 $("#maintainTimeSelectLabel").html("");
	 $("#maintainDateSelDiv").addClass("active in");
	 
}

//选择保养日期之后
function changeDatePickText(obj) {
	//清空选择保养时间
	$("#maintainTimeSelectLabel").html("");
	$("#timeSelectRadioGroup").empty();
	
	var maintainDay = $("#maintainDateSelectText").val();
	alert(maintainDay);
	var bookingType = $("#maintainType").val();
	var rootPath = getRootPath();
	//获取所有的时间列表
	$.ajax({
        type:"GET", 
        url:rootPath+"/wechat/api/maintain/simple?appDay=" + maintainDay+"&bookingType="+bookingType, 
        dataType:"json",      
        async: false,
        contentType:"application/json",               
        data:null, 
        success:function(data){ 
			$.each(data,function(stationIndex,stationStr){
				var appendRadioStr = "<br><input type='radio' name='timeSelectRadio' id='optionsRadios" + stationIndex + "' value='timeSelectRadio" + stationIndex + "'>";
				appendRadioStr += "&nbsp;<label id='timeSelectRadio" + stationIndex + "label'>" + stationStr + "</label>";
				$("#timeSelectRadioGroup").append(appendRadioStr);
			});
			
			//在选择框显示用户选择的保养时间
			$("input:radio[name='timeSelectRadio']").change(function (){
				var radioId = $("input:radio[name='timeSelectRadio']:checked").val() ;
				var labelId = radioId + "label";
				var radioValue = $("#" + labelId).text();
				$("#maintainTimeSelectLabel").html(radioValue);
			});
			
        },
        error:function(data){
        	alert("数据刷新失败，请联系管理员！");
        }
     });
}


//选择保养日期，时间之后确认
function confirmMaintainTime(obj) {
	//校验保养日期有没有选择
	var maintainDate = $("#maintainDateSelectText").val();
	
	//校验保养时间有没有选择
	var maintainTime = $("#maintainTimeSelectLabel").html();
	
	//提醒信息
	var alertStr = "提示：<br>";
	
	//判断是否校验正确标记
	var errFlag = false;
	if (maintainDate == "") {
		alertStr += "保养日期未选择";
		errFlag = true;
	}
	if (maintainTime == "") {
		if (errFlag == true) {
			alertStr += "<br>";
		}
		alertStr += "保养时间未选择";
		errFlag = true;
	}
	
	//校验有错误
	if (errFlag == true) {
		$("#maintainInputErrDiv").addClass("active in");
		$("#maintainInputErrLabel").html(alertStr);
		return;
	}
	//错误提示框隐藏
	$("#maintainInputErrDiv").removeClass("active in");
	$("#maintainInputErrLabel").html("");
	
	
	//主页操作
	//设置主页界面上的日期和时间
	var replaceText = maintainDate + " " + maintainTime;
	$("#selectMaintainTimeLink").html(replaceText);
	//设置主页隐藏的日期和时间
	$("#maintainDate").val(maintainDate);
	$("#maintainTime").val(maintainTime);
	
	$("#maintainMainDiv").addClass("active in");
	$("#maintainDateSelDiv").removeClass("active in");
	$("#maintainDateSelDiv").hide();
	
	
}
/**
 * 设置选择的车型
 * @param index
 * @returns
 */
function setVin(index){
	$("#vin").val($("#vin_"+index).val());
	$("#modelName").val($("#modelName_"+index).val());
}

/**
 * 监听轮播信息
 */
$(function(){
    $('#myCarInfos').on('slid.bs.carousel', function (e) {
    	 var active = $(e.target).find('.carousel-inner > .item.active');
    	 var ccindex = active.index();
    	  $("#vin").val($("#vin_"+ccindex).val());
    	  $("#modelName").val($("#modelName_"+ccindex).val());
    });
});


/**
 * 跳转到绑定车辆页面
 * 
 * @returns
 */
function to_bingCar(){
	
	window.location = rootPath + "/views/vehicleBinding/vehicleBinding.html";
}
/**
 * 跳转到个人中心页面
 * 
 * @returns
 */
function re(){
	window.location = rootPath + "/views/hp.html";
}